package griffin.website;

//import griffin.logic.userLogic.CONSTANT_KEY;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
//import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.content.pm.ActivityInfo;

public class CategoryList extends Activity {
	private static final int FIRSTCATE = 1; // First-class category id's length.
	private static final int SECONDCATE = 3; // Second-class category id's length.
	private static final int THIRDCATE = 5; // Third-class category id's length.
	private static final String TAG = "[categorylist]";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "[onCreate...] ");
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		this.setContentView(R.layout.list);

		showCategoryTitle();
		getCategories();
	}

	private void getCategories() {
		String curcateid = getCurCategoryID();
		SimpleAdapter adapter = new SimpleAdapter(this,
				getCategoryData(curcateid), R.layout.categoryitem,
				new String[] { "categoryName" }, new int[] { R.id.tvTitle });
		ListView listView = (ListView) findViewById(R.id.categorylist);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new CateItemClickListener());
	}

	private void showCategoryTitle() {
		Button btnTitle = (Button) findViewById(R.id.btnCategoryTitle);
		// btnTitle.setText(getCurCategoryName()+getCurCategoryID());
		btnTitle.setText(getCurCategoryName());
		btnTitle.setOnClickListener(new ButtonItemClickListener());
	}

	private String getCurCategoryID() {
		SharedPreferences curcateInfo = getSharedPreferences(
				"griffin.website.curcate", 0);
		return curcateInfo.getString("curcategoryid", "");
	}

	private String getCurCategoryName() {
		SharedPreferences curcateInfo = getSharedPreferences(
				"griffin.website.curcate", 0);
		return curcateInfo.getString("curcategoryname", "");
	}

	private void gotoSubCategory(String cateid) {
		if (cateid.length() == FIRSTCATE || cateid.length() == SECONDCATE) {
			openIntenInView("CategoryList", CategoryList.this);
		} else if (cateid.length() == THIRDCATE) {
			openIntenInView("ContentList", CategoryList.this);
		}
	}

	class CateItemClickListener implements OnItemClickListener {
		public void onItemClick(AdapterView<?> arg0,// The AdapterView where the
				// click happened
				View arg1,// The view within the AdapterView that was clicked
				int arg2,// The position of the view in the adapter
				long arg3// The row id of the item that was clicked
		) {
			HashMap<String, Object> item = (HashMap<String, Object>) arg0
					.getItemAtPosition(arg2);
			displayToast((String) item.get("categoryName"));

			saveCurCategory((String) item.get("categoryID"),
					(String) item.get("categoryName"));
			gotoSubCategory((String) item.get("categoryID"));
		}

		private void saveCurCategory(String curCategoryID,
				String curCategoryName) {
			SharedPreferences curcateInfo = getSharedPreferences(
					"griffin.website.curcate", 0);
			SharedPreferences.Editor editor = curcateInfo.edit();
			if (curcateInfo.contains("curcategoryid"))
				editor.remove("curcategoryid");
			if (curcateInfo.contains("curcategoryname"))
				editor.remove("curcategoryname");
			editor.putString("curcategoryid", curCategoryID);
			editor.putString("curcategoryname", curCategoryName);
			// editor.putString("curcategorynameplu", "");
			editor.commit();
		}
	}

	class ButtonItemClickListener implements OnClickListener {
		public void onClick(View v) {
			// Log.d(TAG,
			// "Categoryid: "+getCurCategoryID()+":"+getCurCategoryName()+"..........................................");
			if (getCurCategoryID().length() == 1) {

//				Intent intent = new Intent();
//				intent.putExtra("winname", "TopHome");
//				intent.setClass(CategoryList.this, TabBarFramework.class);
//				startActivity(intent);

				// Jerry
				CategoryList.this.finish();

			} else {
				SharedPreferences loginInfo = getSharedPreferences(
						"griffin.website.curcate", 0);
				SharedPreferences.Editor editor = loginInfo.edit();
				String strCurCategoryID = getCurCategoryID().substring(0,
						getCurCategoryID().length() - 2);
				if (loginInfo.contains("curcategoryid"))
					editor.remove("curcategoryid");
				if (loginInfo.contains("curcategoryname"))
					editor.remove("curcategoryname");
				editor.putString("curcategoryid", strCurCategoryID);
				editor.putString("curcategoryname",
						getCurCategoryNameNew(strCurCategoryID));
				editor.commit();

				CategoryList.this.finish();
//				Intent intent = new Intent();
//				intent.putExtra("winname", "CategoryList");
//				intent.setClass(CategoryList.this, TabBarFramework.class);
//				startActivity(intent);
			}
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		// userlogic.loginOutWhenExit();
		Log.d(TAG, "[onDestroy...]");
	}

	private String getCurCategoryNameNew(String curCategoryID) {
		String resultStr = "";
		String databaseFilename = TabBarFramework.DATABASE_PATH + "/"
				+ TabBarFramework.DATABASE_FILENAME;
		SQLiteDatabase db;
		db = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);

		Cursor result = null;
		if (curCategoryID.length() == 1) {
			result = db.rawQuery(
					"SELECT VG_NAME  FROM VG_TopCategories where VG_ID="
							+ curCategoryID, null);
		} else {
			result = db.rawQuery(
					"SELECT VG_ENGLISH  FROM VG_WebCategories where VG_ID="
							+ curCategoryID, null);
		}

		if (result.moveToFirst()) {
			while (!result.isAfterLast()) {

				resultStr = result.getString(0);
				result.moveToNext();
			}
		}
		result.close();
		db.close();

		return resultStr;
	}

	private List<Map<String, Object>> getCategoryData(String cateid) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		String databaseFilename = TabBarFramework.DATABASE_PATH + "/"
				+ TabBarFramework.DATABASE_FILENAME;
		SQLiteDatabase db;

		db = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);
		Cursor result = db.rawQuery(
				"SELECT VG_ID, VG_ENGLISH FROM VG_WebCategories where VG_PARENT = "
						+ cateid, null);
		if (result.moveToFirst()) {
			while (!result.isAfterLast()) {
				String categoryid = ((Integer) result.getInt(0)).toString();
				String category = result.getString(1);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("categoryName", category);
				map.put("imgArrow", R.drawable.rightarrow);
				map.put("categoryID", categoryid);
				list.add(map);
				result.moveToNext();
			}
		}
		result.close();
		db.close();

		return list;
	}

	public void displayToast(String str) {
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
	}

	// openIntenInView("register",more.this);
	public void openIntenInView(String name, Context context) {
		Intent intent = new Intent();
		intent.putExtra("winname", name);
		intent.setClass(context, TabBarFramework.class);
		startActivity(intent);
	}

}
